/**
 * Created by Brant on 2016/12/28.
 * 案件设置
 */

module.exports = function ($scope, $state, $rootScope,$cookies,$cookieStore,$location,$window,httpservice,caseBarDetailBarService,caseBarDetailjinchengService,caseBarDetailZhengService,caseBarDetailxiaService) {

    /*获取点击的案件的id*/
    var caseId = $cookies.get('caseAppId');
    var loginId = kbt.decrypt($cookies.get('cookieUserId'));
    /*归档案件和处理案件类型*/
   // var type = $cookies.get('type');
   $scope.type = $cookies.get('type');
  $rootScope.typeIf=$cookies.get('type')

    var caseName = $cookies.get("caseAppName");

    //用户名
    var loginName = kbt.decrypt($cookies.get('cookieUserName'));

    var flag = 1;
  var expireDate= new Date();
  expireDate.setDate(expireDate.getDate() + 1);


    $scope.imgRoot = httpservice.murlWebHttp;

    //案件类别，个人0或者团队1
    $scope.caseowner = "";
    //案件团队ID
    $scope.caseteamid = "";
    // 团队律师添加计数
    $scope.addTeamLawyerCount = 0;
    $scope.addLawyerNewCount = 0;
    $scope.addLawyerAllCount = 0;
    $scope.caseDetail = "1";

    $scope.phoneEmpty = false;
    $scope.phoneValid = false;

    // 主办律师flag
    $scope.hostLawyer = false;

    // 邀请的新律师
    $scope.inviteNewMembers = [];

    // 邀请的平台律师
    $scope.invitedMembers = [];

    /**
     * 初始化
     */
    $scope.caseparentinit = function () {

        getCaseParentDetails();



        $('#CaseBarNav').children('li').click(function () {
            $(this).siblings('li').removeClass('case_active');
            $(this).addClass('case_active');
            var index = $("#CaseBarNav li").index($(this));

            $cookies.put('caseDetailBarIndex', index, {
              expires: expireDate
            });
        });

        /*如果是归档案件，则隐藏设置按钮*/

        /*if (type !== undefined && type == 7) {
            // $("#set-hide").hide();

        }*/


        var favoriteUrl = $cookies.get('favoriteImgUrl') ? $cookies.get('favoriteImgUrl') : "img/wujiao.png";
        if (favoriteUrl == "img/wujiao.png") {
            $("#setCaseTop").html("设置常用");
            flag = 1;
        }else {
            $("#setCaseTop").html("取消常用");
            flag = 0;
        }

        $scope.imgUrl = favoriteUrl;
        $scope.navTitle = $cookies.get("caseAppName");

        var navNum = parseInt(sessionStorage.navNum);
        $('#CaseBarNav').children("li:eq('+navNum+')").addClass('active').siblings('li').removeClass('active');

        // 上次记录的tab位置
        var caseDetailBarIndex = $cookies.get('caseDetailBarIndex');
        if (caseDetailBarIndex != "" && caseDetailBarIndex != null && caseDetailBarIndex != "undefined") {
          $('#CaseBarNav li').removeClass('case_active');
          $('#CaseBarNav li').eq(caseDetailBarIndex).addClass('case_active');
        }

        $scope.phoneEmpty = false;
        $scope.phoneValid = false;
    };

    $scope.$on('noticeCaseName', function (event, args) {
      $scope.navTitle = args.caseName;
    });
    /**
     * 设置常用（案件置顶）
     */
    $scope.favorite = function ($event) {
        $rootScope.loadingShow = true;
        $rootScope.fadeShow = true;
        caseBarDetailBarService.setCaseUsed(caseId,flag).then(function (response) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            if (response.code == 1) {
                if (flag == 1) {
                    /*设置五角星为黄色*/
                    $('.favoriteImg').attr("src", "img/case-star.png");
                    $("#setCaseTop").html("取消常用");
                    flag = 0;
                }else {
                    $('.favoriteImg').attr("src", "img/wujiao.png");
                    $("#setCaseTop").html("设置常用");
                    flag = 1;
                }
                $event.stopPropagation()
            }
        }, function (response) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            console.error('favorite error', response.status, response.statusText);
        });

    };

    /**
     * 归档案件（确认）
     */
    $scope.archiveConfirm = function () {
        /*$rootScope.loadingShow = true;
        $rootScope.fadeShow = true;*/
      bootbox.dialog({
        message: "归档案件后只可查看详情，不可进行其他操作。归档的案件可以撤销归档，并且数据不会丢失，您确定要归档该案件？",
        title: "归档案件",
        className:'d-promptBox',
        buttons: {
          OK: {
            label: "确定",
            className: "d-btn-confirm",

            callback: function () {
              caseBarDetailBarService.setCaseArchive(caseId).then(function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;

                /*请求成功*/
                if (response.code == 1) {
                  // $scope.type=7;
                  /*隐藏确认弹出框*/
                  // #archiveModal").modal('hide');
                  /*跳转到已归档案件列表*/
                  // $state.go('caseBar', {from: 7});
                 /* var urlSx= $location.path();
                  console.log(urlSx.slice(urlSx.lastIndexOf('/')+1,urlSx.length));*/
                 $rootScope.typeIf=7;
                  $cookieStore.remove("type");
                  $cookies.put('type', $rootScope.typeIf, {//已归档和处理中类型
                    expires: expireDate
                  });

                  // getCaseParentDetails()
                  // $state.go("caseBarDetailxia", {type:$rootScope.typeIf});
                  if(response.data==null){
                    $('.caseBar_kong').addClass('.caseBar_list');
                  }else {
                    $('.caseBar_kong').removeClass('.caseBar_list');
                  }
                  // $window.location.reload();
                } else {
                  bootbox.alert({
                    size: "small",
                    title: "提示信息",
                    message: response.message,
                    callback: function(){ /* your callback code */ }
                  });
                }
              }, function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                console.error('setCaseArchive error', response.status, response.statusText);
              });
            }
          },
          Cancel: {
            label: "取消",
            className: "d-btn-cancel",
            callback: function () {

            }
          }
        }
      });

    };

    /**
     * 归档案件（取消）$scope.archiveCancel
     */
    $scope.archiveCancel = function () {
      bootbox.dialog({
        message: "撤销归档后，可以对该案件进行所有操作。您确定要撤销该案件归档？",
        title: "撤销归档",
        className:'d-promptBox',
        buttons: {
          OK: {
            label: "确定",
            className: "d-btn-confirm",

            callback: function () {
              caseBarDetailBarService.setCaseUnArchive(caseId).then(function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                /*请求成功*/
                if (response.code == 1) {
                  /*隐藏确认弹出框*/
                  // $("#archiveModal").modal('hide');
                  /*跳转到已归档案件列表*/
                  $rootScope.typeIf=1;
                  $cookieStore.remove("type");
                  $cookies.put('type',1, {//已归档和处理中类型
                    expires: expireDate
                  });

                  // $state.go('caseBar', {from: 1});
                  if(response.data==null){
                    $('.caseBar_kong').addClass('.caseBar_list');
                  }else {
                    $('.caseBar_kong').removeClass('.caseBar_list');
                  }
                } else {
                  bootbox.alert({
                    size: "small",
                    title: "提示信息",
                    message: response.message,
                    callback: function(){ /* your callback code */ }
                  });
                }
              }, function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                console.error('setCaseArchive error', response.status, response.statusText);
              });
            }
          },
          Cancel: {
            label: "取消",
            className: "d-btn-cancel",
            callback: function () {

            }
          }
        }
      });










       /* /!*隐藏确认弹出框*!/
        $("#archiveModal").modal('hide');
        $('.modal-backdrop').hide();*/
    };

    /**
     * 删除案件（确定删除）
     */
    $scope.deleteConfirm = function () {

      bootbox.dialog({
        message: "此案件删除不可修复，确定删除",
        title: "提示信息",
        className:'d-promptBox',
        buttons: {
          OK: {
            label: "确定",
            // className: "btn-default",
            className: "d-btn-confirm",
            // confirmButtonColor: "#DD6B55",
            callback: function () {
              caseBarDetailBarService.deleteCase(caseId,loginName).then(function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                /*请求成功*/
                if (response.code == 1) {
                  /*隐藏确认弹出框*/
                  // $("#deleteModal").modal('hide');
                  $state.go('caseBar', {from: 1});
                  $(this).removeClass('L_caseBaseIcon');
                  $(this).removeClass('L_caseBaseP');
                  // $scope.addRole.caseSetMore = false;
                }
                // else {
                //     bootbox.alert({
                //         size: "small",
                //         title: "提示信息",
                //         message: response.message,
                //         callback: function(){ /* your callback code */ }
                //     });
                //   $scope.addRole.caseSetMore == false;
                // }
              }, function (response) {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
                console.error('deleteConfirm error', response.status, response.statusText);
              });
            }
          },
          Cancel: {
            label: "取消",
            // className: "btn-default",
            className: "d-btn-cancel",
            // confirmButtonColor: "#DD6B55",
            callback: function () {
            }
          }
        }
      });
        // $rootScope.loadingShow = true;
        // $rootScope.fadeShow = true;
    };

    /**
     * 取消删除案件
     */
    $scope.deleteCancel = function () {
        /*隐藏确认弹出框*/
        $("#deleteModal").modal('hide');
    };


    /**
     * 退出案件（确定退出）
     */
    $scope.exitConfirm = function () {

        $rootScope.loadingShow = true;
        $rootScope.fadeShow = true;
        caseBarDetailBarService.exitCase(caseId,caseName).then(function (response) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            /*请求成功*/
            if (response.code == 1) {
                /*隐藏确认弹出框*/
                $("#exitModal").modal('hide');
                $state.go('caseBar', {from: 1});
            } else {
                bootbox.alert({
                    size: "small",
                    title: "提示信息",
                    message: response.message,
                    callback: function(){ /* your callback code */ }
                });
            }
        }, function (response) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            console.error('exitConfirm error', response.status, response.statusText);
        });

    };

    /**
     * 取消退出案件
     */
    $scope.exitCancel = function () {
        /*隐藏确认弹出框*/
        $("#exitModal").modal('hide');
    };


    $scope.caseparentinit();
    //设置角色
    $scope.showLawyerInfo = showLawyerInfo;
    $scope.showLawyerRole = showLawyerRole;
    $scope.setType = setType;
    $scope.setDel = setDel;
    $scope.setLawyerRole = setLawyerRole;
    //案件设置
    $scope.caseBarSetBase = caseBarSetBase;
    $scope.caseBarSetNav = caseBarSetNav;
    $scope.caseBarSetMember = caseBarSetMember;
    $scope.caseBarSetMore = caseBarSetMore;
    $scope.caseBarSetClose = caseBarSetClose;
    $scope.caseBarSetAll = caseBarSetAll;
    $scope.caseBaseSet = caseBaseSet;
    //添加律师
    $scope.closeLawyer = closeLawyer;
    $scope.openLawyer = openLawyer;
    $scope.directLawyer = directLawyer;
    $scope.inviteLawyer = inviteLawyer;
    $scope.saveCaseRole = saveCaseRole;
    $scope.deletebarrister = deletebarrister;
    // $scope.mParties3 = mParties3;
    $scope.dislodgehostLawyer = dislodgehostLawyer;
    $scope.setbarristername = setbarristername;
    $scope.saveEmailLawyer = saveEmailLawyer;
    $scope.modification = modification;
    //获取案件详情
    $scope.getCaseParentDetails = getCaseParentDetails;
    //关闭角色设置
    $scope.addPopupTopClose = addPopupTopClose;
    // 案件律师邀请
    $scope.getCaseLawyerSingle = getCaseLawyerSingle;

    // 获取律师列表
    // $scope.getInviteMemberList = getInviteMemberList;

    //律师区分类别
    var caselvshitype = 1;
    /**律师成员的集合页面获取的*/
    var lawyersbarrister = new Array();

    //案件基本
    $scope.caseBase = {};
    //案件名称
    $scope.caseBase.caseName = $scope.navTitle;
    //律师信息
    $scope.caseLawyerInfor = {};
    //获取律师列表
    // $scope.inviteMemberList = [];
    $scope.invitedTempMembers = [];

  $scope.addRole = {
      role:false,//角色
      type:false,//角色类型
      setLawyerRole:false,//设置主办律师角色
      caseBarAll:false,//案件整体
      caseSetBase:false,//案件基本信息
      caseSetNav:false,//案件导航
      caseSetMember:false,//案件成员
      caseSetMore:false,//案件更多
      casePigeonhole:false,//归档
      invited:false,//邀请
    };

  //案件设置
  $scope.caseSet = caseSet;
  function caseSet(ev) {
    var ev=ev||event;

    $scope.addRole.caseBarAll = true;
    $scope.addRole.caseSetBase = true;
    $scope.addRole.casePigeonhole = false;


  }

  function delHtmlTag(str){
    if(str) {
      return str.replace('/<[^>]+>/g',"");//去掉所有的html标记
    } else{
      return "";
    }
  }

  //获取案件详情 接口
  $scope.caseLawyers = [];
  function getCaseParentDetails() {

    caseBarDetailxiaService.getCaseDetails(caseId).then(function (data) {
      if(data.code == 1){
        //案件信息
        $scope.caseDetail = data.data.case;
        //参与律师
        $scope.caseLawyers = data.data.caseLawyers;

        $scope.hostTypeList= [];
        $scope.caseSourceTypeList= [];
        $scope.managerTypeList= [];
        $scope.helpTypeList= [];

        for(var i=0;i<$scope.caseLawyers.length;i++){
          if($scope.caseLawyers[i].lawyertypeid == 1){
            $scope.caseLawyerHost = $scope.caseLawyers[i].lawyer.id;
            //主办律师的类型
            $scope.hostType = $scope.caseLawyers[i].lawyertypeid;
            $scope.hostTypeList.push($scope.caseLawyers[i]);
          }else if($scope.caseLawyers[i].lawyertypeid == 2){
            //案源律师的类型
            $scope.caseSourceType = $scope.caseLawyers[i].lawyertypeid;
            $scope.caseSourceTypeList.push($scope.caseLawyers[i]);
          }else if($scope.caseLawyers[i].lawyertypeid == 3){
            //助理律师的类型
            $scope.managerType = $scope.caseLawyers[i].lawyertypeid;
            $scope.managerTypeList.push($scope.caseLawyers[i]);
          }else if($scope.caseLawyers[i].lawyertypeid == 4){
            //协办律师的类型
            $scope.helpType = $scope.caseLawyers[i].lawyertypeid;
            $scope.helpTypeList.push($scope.caseLawyers[i]);
          }
        }

        for(var i=0;i<$scope.hostTypeList.length;i++){
          if($scope.hostTypeList[i].lawyer.id == loginId ) {
            $scope.hostLawyer = true;
            break;
          }
        }


        sortLawyer();
        //案件概述
        $scope.summary = data.data.case.summary;
        //诉讼请求
        $scope.demand = data.data.case.demand;
        //案件类别，个人0或者团队1
        $scope.caseowner = data.data.case.caseOwner;
        //案件团队ID
        $scope.caseteamid = data.data.case.teamid;
        // 0 : 直接添加  1 : 邀请
        $scope.alertTabShow = 0;
        if ($scope.caseowner == 0)
          $scope.alertTabShow = 1;
        if(delHtmlTag($scope.summary)==''){
          $('.L_summary').css('display','block');
        }else {
          $('.L_summary').css('display','none');
        }

        if(delHtmlTag($scope.demand)==''){
          $('.L_demand').css('display','block');
        }else {
          $('.L_demand').css('display','none');
        }

        // 通知子窗口刷新案件详情
        $scope.$broadcast('refreshCaseDetail', data);
      }
    }
    );
  }


  function showLawyerRole(type) {
    switch (type) {
      case 1 : return "主办";
      case 2 : return "案源";
      case 3 : return "助理";
      case 4 : return "协办";
    }
  }

  function sortLawyer() {

    for(var i=0; i<$scope.caseLawyers.length; i++){
      if($scope.caseLawyers[i].lawyertypeid == 1){
        // 主办
        $scope.caseLawyers[i].seq = 1;
      } else if($scope.caseLawyers[i].lawyertypeid == 4){
        // 承办
        $scope.caseLawyers[i].seq = 2;
      } else if($scope.caseLawyers[i].lawyertypeid == 3){
        // 助理
        $scope.caseLawyers[i].seq = 3;
      } else if($scope.caseLawyers[i].lawyertypeid == 2){
        // 案源
        $scope.caseLawyers[i].seq = 4;
      }
    }
  }

  //展示律师
  function showLawyerInfo(caseLawyer,event) {

    if($rootScope.typeIf!=7){
      $('#showLawyer').css('display','block');
    }

    event.stopPropagation();
    $scope.caseLawyerInfor = caseLawyer;

     $scope.addRole.role = true;
    if($scope.caseLawyerHost == loginId){
     // $scope.addRole.role = true;
    }
    // if($scope.caseLawyerInfor.lawyertypeid == 1){
    //   if($scope.caseLawyerInfor.lawyer.id == loginId){
    //     $scope.addRole.role = true;
    //   }
    // }else {
    //   $scope.addRole.role = false;
    // }
    // $('#showLawyer').popover(options);
    // $event.stopPropagation();
    // $scope.addRole.role = $event.target.innerHTML;
    // if($scope.caseLawyerInfor.lawyertypeid == 1){
    //   $scope.addRole.setLawyerRole = true;
    //   return;
    // }else if($scope.caseLawyerInfor.lawyertypeid != 1){
    //   $scope.addRole.role = true;
    // }
  }
  //主办律师不能设置关闭
  function setLawyerRole() {
    //$scope.addRole.setLawyerRole = false;
  }
    //保存角色 接口
  function saveCaseRole(type) {
    event.stopPropagation();
    var params={"caseLawyerId":$scope.caseLawyerInfor.id,"caseId":caseId,"roleId":type};
    caseBarDetailBarService.caseRoleSet(params).then(function (response) {
      if(response.data.code == 1){
        $scope.caseLawyerInfor.lawyertypeid = type;
        $scope.addRole.role = false;
        $scope.addRole.type = false;
        $scope.getCaseParentDetails();
      }
      $scope.addRole.type = false;
    });
  }


  //删除律师
  function deletebarrister(index) {//caseId
    var params = {"caseId":caseId,"caseLawyerId":$scope.caseLawyerInfor.id};
    caseBarDetailxiaService.deletebarrister(params).then(function (data) {
      if(data.code==1){
        $scope.managerTypeList.splice(1,1);
        // $scope.$watch('managerTypeList',function(){
        //   $scope.managerTypeList;
        // },true);

        // 在全部律师范围内删除
        for(var index = 0; index < $scope.caseLawyers.length; index++){
          if($scope.caseLawyers[index].id == $scope.caseLawyerInfor.id){
            $scope.caseLawyers.splice(index, 1);
          }
        }
        // 主办律师的类型
        for(var index = 0; index < $scope.hostTypeList.length; index++){
          if($scope.hostTypeList[index].id == $scope.caseLawyerInfor.id){
            $scope.hostTypeList.splice(index, 1);
          }
        }
        // 案源律师的类型
        for(var index = 0; index < $scope.caseSourceTypeList.length; index++){
          if($scope.caseSourceTypeList[index].id == $scope.caseLawyerInfor.id){
            $scope.caseSourceTypeList.splice(index, 1);
          }
        }
        // 助理律师的类型
        for(var index = 0; index < $scope.managerTypeList.length; index++){
          if($scope.managerTypeList[index].id == $scope.caseLawyerInfor.id){
            $scope.managerTypeList.splice(index, 1);
          }
        }
        // 协办律师的类型
        for(var index = 0; index < $scope.helpTypeList.length; index++){
          if($scope.helpTypeList[index].id == $scope.caseLawyerInfor.id){
            $scope.helpTypeList.splice(index, 1);
          }
        }
      }
    })
  }

    //设置角色类型
    function setType() {
      $scope.addRole.type = !$scope.addRole.type;
    }
    //移除
    function setDel(index) {
      $scope.addRole.role = false;
      $scope.addRole.type = false;
      deletebarrister(index);
    }
    function caseBarSetAll($event) {


      // $scope.addRole.caseBarAll = true;
      // $scope.addRole.caseSetBase = true;
      $('.setting-case').removeClass('hide');
      $scope.addRole.casePigeonhole = !$scope.addRole.casePigeonhole;

        $event.stopPropagation();

      // caseBaseSet();

    }
    //关闭角色设置
    function addPopupTopClose() {
      $scope.addRole.role = false;
      $scope.addRole.type = false;
    }


  //案件设置(基本信息)
  function caseBarSetBase() {
    $scope.addRole.caseSetBase = true;
    $scope.addRole.caseSetNav = false;
    $scope.addRole.caseSetMember = false;
    $scope.addRole.caseSetMore = false;
  }
  //案件设置(导航设置)
  function caseBarSetNav() {
    $scope.addRole.caseSetNav = true;
    $scope.addRole.caseSetBase = false;
    $scope.addRole.caseSetMember = false;
    $scope.addRole.caseSetMore = false;
  }
  //案件设置（成员管理）
  function caseBarSetMember() {
    $scope.addRole.caseSetMember = true;
    $scope.addRole.caseSetBase = false;
    $scope.addRole.caseSetNav = false;
    $scope.addRole.caseSetMore = false;

  }
  //案件设置(更多)
  function caseBarSetMore() {
    $scope.addRole.caseSetMore = true;
    $scope.addRole.caseSetBase = false;
    $scope.addRole.caseSetNav = false;
    $scope.addRole.caseSetMember = false;
  }
  //案件设置（关闭）
  function caseBarSetClose() {
    $scope.addRole.caseBarAll = false;
    $scope.addRole.caseSetMember = false;
    $scope.addRole.caseSetBase = true;
    $scope.addRole.caseSetNav = false;
    $scope.addRole.caseSetMore = false;
  }

  //案件基本信息接口
  function caseBaseSet() {
    var params={"caseName":$scope.caseBase.caseName,"caseId":caseId};
    caseBarDetailBarService.caseBaseSet(params).then(function (response) {
      if(response.data.code==1){
        $scope.navTitle = $scope.caseBase.caseName;
      }
    })
  }

  //添加律师
  $scope.showAddWindow = {
    addLawyer:false,
    direct:true,//直接添加
    invite:false,//邀请添加
  };

  //直接添加
  function directLawyer() {
    $scope.showAddWindow.direct = true;
    $scope.showAddWindow.invite = false;
  }
  //邀请添加
  function inviteLawyer() {
    $scope.showAddWindow.invite = true;
    $scope.showAddWindow.direct = false;
  }
  $scope.person = {};
  $scope.lawyerList = {};

  //打开团队律师列表弹窗
  function openLawyer() {
    if($rootScope.typeIf!=7){
      getPartnerLawsList();
      angular.element('#myModalInviteLaywer').modal('show');
      $scope.showAddWindow.addLawyer = true;
      $scope.alertTabShow=1;
      $('.LawyerAddBody-xia').show();//css('display','block');

      // 清空团队律师计数
      $scope.addTeamLawyerCount = 0;
      $scope.addLawyerAllCount = 0;
      $scope.addLawyerNewCount = 0;
      $scope.inviterEmail = '';
      $scope.phoneEmpty = false;
      $scope.phoneValid = false;

      $scope.invitedMembers = [];
      $scope.inviteNewMembers = [];
    }

  }

  //关闭团队律师列表弹窗
  function closeLawyer() {
    angular.element('#myModalInviteLaywer').modal('hide');
    $scope.showAddWindow.addLawyer = false;
    $('.LawyerAddBody-xia').css('display','none');
    // 清空律所律师列表
    $scope.CaseLawyerTianSelect = [];
    $scope.caseowner = 1;
    $scope.keyword = "";
    $scope.inviterEmail = "";
  }
  //获取律师
  $scope.mParties3 = function () {
    $(document).keyup(function (event) {
      //查询律师成员接口
      if (event.keyCode == 13) {
        getPartnerLawsList();
      }
    });
  };

  /**添加律师成员*/
  function setbarristername(data) {
    //列表
    $scope.CaseLawyerTianSelect = data.data;

    //修改律师
    $scope.CaseLawyerTianButton = function (name, LawyerId, LawyerIcon) {
      $scope.CaseLawyerTianModel = name;
      $scope.LawyerId = LawyerId;
      $scope.LawyerIcon = LawyerIcon;
      if (caselvshitype == 1) {
        //去除律师
        dislodgehostLawyer(lawyersbarrister, 1);
      }
      if (caselvshitype == 2) {
        //去除律师
        dislodgehostLawyer(lawyersbarrister, 2);
      }
      if (caselvshitype == 3) {
      }

      var hostLawyer = new Object();
      //  hostLawyer.id = null;
      hostLawyer.lawyerId = LawyerId;
      hostLawyer.lawyerType = parseInt(caselvshitype);
      lawyersbarrister.push(hostLawyer);
      //修改律师
      modification($scope.CaseLawyerTianModel, $scope.LawyerId, LawyerIcon);

      // $(".addlvshi1").on("click", function () {
      //   // $(".LawyerAddBody-xia").show();
      //   $scope.showAddWindow.addLawyer = true;
      // });
      // $(".LawyerAddBody-xia").hide();
      $scope.showAddWindow.addLawyer = false;
    };

    //点击关闭
    // $scope.CaseLawyerClose = function () {
    //   $scope.CaseLawyerTianModel = "";
    //   // $("#LawyerBox").css("display","none");
    //   $scope.showAddWindow.addLawyer = false;
    // };

    $(".LawyerboxUlbutton").show()
  }

  /**
   * 去除多余的律师
   * @param lawyers
   * @param inx
   */
  function dislodgehostLawyer(lawyers, inx) {

    for (var i = 0; i < lawyers.length; i++) {
      if (lawyers[i].lawyertypeid == inx) {
        lawyers.splice(i, 1);
      }
    }
  }

  /**修改律师*/
  function modification(name, ybid, icon) {
    var obj = new Object();
    obj.caseId = caseId;
    if (caselvshitype == 1) {
      if ($scope.lawyerIdmajor == 0) {
        obj.id = null
      } else {
        obj.id = $scope.lawyerIdmajor
      }
      obj.lawyerType = 1;
    } else if (caselvshitype == 2) {
      if ($scope.SourcesID == null) {
        obj.id = null
      } else {
        obj.id = $scope.SourcesID
      }
      obj.lawyerType = 2;
    } else if (caselvshitype == 3) {
      obj.lawyerType = 3;
    }
    obj.lawyerId = ybid;
    obj.lawyerName = name;
    obj.userId = $scope.loginId;
    obj.caseName = caseName;
    obj.userName = loginName;
    obj.lawyerIcon = icon;
    // $scope.casejson = JSON.stringify(obj);

    $scope.casejson = obj;

    $rootScope.loadingShow = true;
    $rootScope.fadeShow = true;
    //添加案源律师
    caseBarDetailxiaService.modificationbarrister($scope.casejson).then(function (data) {
      $rootScope.loadingShow = false;
      $rootScope.fadeShow = false;
      if (data.code == 1) {
        // 添加律师后，不重新查询参与律师，直接构造一个律师在前台显示
        var newCaseLawyer = new Object();
        newCaseLawyer.id = ybid;
        var lawyer = new Object();
        lawyer.iconUrl = icon;
        newCaseLawyer.lawyer = lawyer;
        // 默认协助律师
        newCaseLawyer.lawyertypeid = 3;
        $scope.caseLawyers.push(newCaseLawyer);
        sortLawyer();

        for(var i=0; i<$scope.CaseLawyerTianSelect.length; i++){
          if($scope.CaseLawyerTianSelect[i].Id == ybid){
            $scope.CaseLawyerTianSelect[i].flag = 3;
          }
        }
        $scope.addTeamLawyerCount = $scope.addTeamLawyerCount + 1;
        // $scope.mReminderheadline="邀请律师提示";
        //主办律师
        if (caselvshitype == 1) {
          // $(".ZhuLawyer_img").hide();
          //  $('.ZhuLawyer_title').hide();
          //    $("#ZhuLawyer").html("<div class='addlvshi' style='background-color: rgb(66,183,159);color:#fff;'><span style='margin-top: 0px;'>" + name + "</span></div><span>主案律师</span>");
          // $scope.mRemindertxt="已给主办律师<p style='color:red'>"+name+"</p>发送邀请！请耐心等待";
          //案源律师
        } else if (caselvshitype == 2) {
          /* $(".Sources1").show();
           $(".Sources").hide();

           $scope.SourcesUsername = name
           //案源律师ID
           $scope.SourcesID = data.id*/
          // $scope.mRemindertxt="已给案源律师<p style='color:red'>"+name+"</p>发送邀请！请耐心等待";
          //协助律师
        } else if (caselvshitype == 3) {
          /*  //协助律师对象
           var obj = new Object();
           obj.lawyerid = ybid;
           obj.username = name;
           obj.id = data.id;

           CaseLawyersList.push(obj);

           $scope.CaseLawyers = CaseLawyersList*/
          // $scope.mRemindertxt="已给协助律师<p style='color:red'>"+name+"</p>发送邀请！请耐心等待";
        }else if(caselvshitype == 4){
          /*  //承办律师对象
           var obj = new Object();
           obj.lawyerid = ybid;
           obj.username = name;
           obj.id = data.id;

           CaseLawyersList.push(obj);

           $scope.CaseLawyers = CaseLawyersList*/
          // $scope.mRemindertxt="已给协助律师<p style='color:red'>"+name+"</p>发送邀请！请耐心等待";
        }
      } else {
        // alert(data.msg);
        $scope.mRemindertxt=data.msg;
      }
      // $("#myBarrister").modal("show");
      lawyersbarrister = [];
      /**刷新页面*/
      // $scope.getCaseDetails();


    }, function (response) {
      $rootScope.loadingShow = false;
      $rootScope.fadeShow = false;
      console.error('updatemessage error', response.status, response.statusText);
    });
  }


  //出现添加律师成员的列表,获取请求
  // $(".addlvshi1").on("click", function () {
  //
  //   $(".LawyerAddBody-xia").css("display","block");
  //   $rootScope.loadingShow = true;
  //   $rootScope.fadeShow = true;
  //   caseBarDetailZhengService.getLawyers(caseId).then(function (data) {
  //     $rootScope.loadingShow = false;
  //     $rootScope.fadeShow = false;
  //     if (data.code == 1) {
  //       $scope.CaseLawyerTianSelect = data.data;
  //     }
  //   });
  //
  // });

  // 案件律师邀请
  function getCaseLawyerSingle() {
    $scope.invitedTempMembers = [];
    // 后台请求参数
    $scope.invite = [];
    $scope.invite.caseId = caseId;
    $scope.invite.inviterEmail = $scope.inviterEmail;

    caseBarDetailBarService.caseGetMemberSingleUrl($scope.invite).then(function (response) {
      if(response.code == 1){
        $scope.invitedTempMembers = response.data;
      }
    });

  }

  //邮箱邀请律师
  function saveEmailLawyer() {
    $rootScope.loadingShow = true;
    $rootScope.fadeShow = true;
    // $scope.person = {"keyword":$scope.person.keyword};
    var params = {"caseId":caseId,"inviterEmail":$scope.inviterEmail};
    caseBarDetailBarService.saveEmailLawyer(params).then(function(response) {
      if(response.data.code == 1){
        // $scope.inviteNewMembers = [];
        // $scope.invitedMembers = [];
        $scope.invitedTempMembers = [];
        var lawyerinfo = response.data.data;
        $scope.inviterEmail = "";

        if (!lawyerinfo.register) {
          $scope.addLawyerNewCount = $scope.addLawyerNewCount + 1;
          $scope.addLawyerAllCount = $scope.addLawyerAllCount + 1;
          // 邀请的未注册用户
          $scope.inviteNewMembers.push(lawyerinfo);

        } else {
          $scope.addLawyerAllCount = $scope.addLawyerAllCount + 1;
          // 添加律师后，不重新查询参与律师，直接构造一个律师在前台显示
          // var newCaseLawyer = new Object();
          // newCaseLawyer.id = lawyerinfo.id;
          // var lawyer = new Object();
          // if (lawyerinfo.icon != '')
          //   lawyer.iconUrl = lawyerinfo.icon;
          // lawyer.username = lawyerinfo.name;
          // lawyer.email = lawyerinfo.email;
          // newCaseLawyer.lawyer = lawyer;
          // // 默认协助律师
          // newCaseLawyer.lawyertypeid = 3;
          // $scope.caseLawyers.push(newCaseLawyer);
          // sortLawyer();

          // 邀请的注册用户
          $scope.invitedMembers.push(lawyerinfo);

          // 添加至协助律师
          caseBarDetailBarService.caseLawyersUrl(params).then(function(response) {

            if(response.data.code == 1){
              $scope.caseLawyers = response.data.data;

              $scope.hostTypeList= [];
              $scope.caseSourceTypeList= [];
              $scope.managerTypeList= [];
              $scope.helpTypeList= [];

              for(var i=0;i<$scope.caseLawyers.length;i++){
                if($scope.caseLawyers[i].lawyertypeid == 1){
                  $scope.caseLawyerHost = $scope.caseLawyers[i].lawyer.id;
                  //主办律师的类型
                  $scope.hostType = $scope.caseLawyers[i].lawyertypeid;
                  $scope.hostTypeList.push($scope.caseLawyers[i]);
                }else if($scope.caseLawyers[i].lawyertypeid == 2){
                  //案源律师的类型
                  $scope.caseSourceType = $scope.caseLawyers[i].lawyertypeid;
                  $scope.caseSourceTypeList.push($scope.caseLawyers[i]);
                }else if($scope.caseLawyers[i].lawyertypeid == 3){
                  //助理律师的类型
                  $scope.managerType = $scope.caseLawyers[i].lawyertypeid;
                  $scope.managerTypeList.push($scope.caseLawyers[i]);
                }else if($scope.caseLawyers[i].lawyertypeid == 4){
                  //协办律师的类型
                  $scope.helpType = $scope.caseLawyers[i].lawyertypeid;
                  $scope.helpTypeList.push($scope.caseLawyers[i]);
                }
              }

              for(var i=0;i<$scope.hostTypeList.length;i++){
                if($scope.hostTypeList[i].lawyer.id == loginId ) {
                  $scope.hostLawyer = true;
                  break;
                }
              }
            }
          });
        }

      }else if(response.data.code == 0){
        // $scope.addRole.invited = true;
        $scope.invitedMsg = response.data.msg;
        // $scope.showAddWindow.addLawyer = false;
      }

      $rootScope.loadingShow = false;
      $rootScope.fadeShow = false;
    }, function () {
      $rootScope.loadingShow = false;
      $rootScope.fadeShow = false;
    })
  }

  // 取得团队律师列表
  function getPartnerLawsList() {
    $rootScope.loadingShow = true;
    $rootScope.fadeShow = true;
    caseBarDetailxiaService.CaseLawyerTian($scope.keyword, $scope.caseteamid, caseId).then(function (data) {
      $('.LawyerboxUl').show();
      $('.LawyerboxUl').css("height", "100px");
      $('.LawyerAddBody-xia').css("min-height", "230px");
      if (data.code == 1) {
        setbarristername(data);
      } else {
        $(".LawyerboxUlS").html("请检查输入是否正确");
        $(".LawyerboxUlbutton").hide()
      }
      $rootScope.loadingShow = false;
      $rootScope.fadeShow = false;

    }, function () {
      $rootScope.loadingShow = false;
      $rootScope.fadeShow = false;
    });
  }

  // //获取案件直接邀请的律师
  // function getInviteMemberList(id) {
  //   var params = {'id': id};
  //   teamService.getTeamMember(params).then(function (response) {
  //     if (response.data.code == 1) {
  //       $scope.inviteMemberList = response.data.data;
  //     }
  //   })
  // }
  //邮箱邀请验证
  $scope.phoneEmpty = false;
  $scope.phoneValid = false;
  $scope.invitationEmailCase = invitationEmailCase;
  // $scope.checkMobileOrganiza = checkMobileOrganiza;
  function invitationEmailCase(){
    var phone = $scope.inviterEmail;
    var myreg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
    if(phone == ''){
      $scope.phoneEmpty = true;
    }
    else if(!myreg.test(phone)){
      $scope.phoneValid = true;
    }else{
      $scope.phoneEmpty = false;
      $scope.phoneValid = false;
    }
    return false;
  }
  $(document).click(function () {
    if ($scope.addRole.casePigeonhole) {
      $scope.addRole.casePigeonhole = false;
      $('.setting-case').addClass('hide');
    };
    $('#collapseExample').animate({'right':'-80px'},400);
    $('#showLawyer').css('display','none');
    // if($('#collapseExample').hasClass('in')){
    //   $('#collapseExample').removeClass('in');
    //   $('#L_lawyerList').removeClass('L_lawyerListActive');
    //   $('.L_lawyerListNum').removeClass('L_lawyerListActive');
    // }else {
    //   $('#L_lawyerList').addClass('L_lawyerListActive');
    //   $('.L_lawyerListNum').addClass('L_lawyerListActive');
    // }
  });

  $('.well').click(function (event) {
    event.stopPropagation();
  });



  $('#L_lawyerList').click(function (ev) {
    var ev=ev||event;
    ev.stopPropagation();
    $('#collapseExample').animate({'right':'0px'},400);
    $('#collapseExample').css('display','block');
    $('#L_lawyerList').css('color',"#00BFB5");
    $('.L_lawyerListNum').css('color',"#00BFB5");
  });

  $('.L_lawyerListClose').click(function () {
    $('#collapseExample').animate({'right':'-80px'},400);
    $('#L_lawyerList').css('color',"#333");
    $('.L_lawyerListNum').css('color',"#333");
    // $('#collapseExample').css('display','none');
  });

};
